const {deleteData} = require("../../DAO");
const db = require('../../db/sql')
const knex = require("../../db/knex");

/**
 * 删除角色及角色-权限对应关系
 * @param params  角色id,role_id
 * @param res  响应对象
 * @returns {Promise<void>}
 */
async function deleteRole(params, res) {
//     let sql = `DELETE FROM roles WHERE role_id = ${params};
// DELETE FROM role_permission WHERE role_id = ${params}`
    // let {role_id,role_name,permissions,description} = params
    // 定义两个SQL语句
    let isErr = false
    //如果角色已被分配,则不能删除
    await knex.transaction(async trx => {
        let search = await trx('roles').select('*').where({role_id: params})
        let userresult = await trx('userlist').select({role: search[0].role_description})
        if (userresult.length > 0) {
            isErr = true
        }
    })
    if (isErr) {
        res.sendStatus(409)
        return
    }
    let updateRoleTableSQL = `DELETE FROM roles WHERE role_id = ${params}`;
    let updatePermissionTableSQL = `DELETE FROM role_permission WHERE role_id = ${params}`;
// 使用Promise实例对象来包装两个SQL语句
    let updateRoleTablePromise = new Promise((resolve, reject) => {
        db.query(updateRoleTableSQL, (err, result) => {
            if (err) {
                reject(err);
            } else {
                resolve(result);
            }
        });
    });
    let updatePermissionTablePromise = new Promise((resolve, reject) => {
        db.query(updatePermissionTableSQL, (err, result) => {
            if (err) {
                reject(err);
            } else {
                resolve(result);
            }
        });
    });
// 使用Promise.all()实现同时执行两个SQL语句
    Promise.all([
        updateRoleTablePromise,
        updatePermissionTablePromise
    ]).then(result => {

        console.log('两个SQL语句执行完毕');
        res.send({
            code: 200,
            msg: '删除成功'
        })
    }).catch(err => {
        res.send({
            code: 500,
            msg: '删除失败'
        })
        console.log(err)
    });
}


module.exports = deleteRole
